<?php

namespace App\Console\Commands\Redis;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class serieLoginUserCount extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'redis:active';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
      $this->doItUseHyperloglog();
//      $this->doItUseBitmap();
    }

    private function doItUseHyperloglog() {
      $this->loginSetUseHyperloglog();
    }

    private function loginSetUseHyperloglog() {

      $pf_keys = [];

      Redis::multi();
      for ($date = 20210713; $date <= 20210717; $date++) {

        $min_uid = rand(1, 10000);
        $max_uid = rand(1, 10000);
        if ($min_uid > $max_uid) {
          $temp_uid = $min_uid;
          $min_uid = $max_uid;
          $max_uid = $temp_uid;
        }
        for ($i = $min_uid; $i <= $max_uid; $i++) {
          $key = $date.'_user_login';
          Redis::pfadd($key, $i);
          $pf_keys[] = $key;
        }
      }
      Redis::exec();

      $series_days_active_user_count = Redis::pfcount(...$pf_keys);

      var_dump($series_days_active_user_count);
    }


    private function doItUseBitmap() {
      $this->loginSet();
      $this->getActiveCount();
    }

    // 设置5天登录的用户
    private function loginSet() {
      Redis::multi();
      for ($date = 20210713; $date <= 20210717; $date++) {
        for ($uid = 1; $uid <= 1000; $uid++) {
          $isgLogin = rand(1, 10) > 5 ? 1 : 0;
          Redis::setbit($date.'_user_login', $uid, $isgLogin);
        }
      }

      Redis::exec();
    }

    // 获得所有总数
    private function getActiveCount() {
      $keys = [];
      for ($date = 20210713; $date <= 20210717; $date++) {
        $keys[] = $date.'_user_login';
      }

      $dest = '5daysloginedcount';
      Redis::bitop('and', $dest, ...$keys);
      var_dump(Redis::bitcount($dest));
    }
}
